<!--
 * @Description: 公益站管理
 * @Author: 龙春雨
 * @Date: 2023-04-10 15:22:41
-->
<template>
  <basic-container>
    <avue-crud
      ref="crud"
      v-model="form"
      class="base-crud"
      :page.sync="page"
      :data="tableData"
      :table-loading="tableLoading"
      :option="tableOption"
      :before-open="beforeOpen"
      :upload-before="uploadBefore"
      :upload-after="uploadAfter"
      :upload-exceed="uploadExceed"
      :upload-error="uploadError"
      :upload-change="$uploadChange"
      @on-load="getList"
      @search-change="searchChange"
      @search-reset="searchReset"
      @row-update="handleUpdate"
      @row-save="handleSave"
      @row-del="handleDelete"
    >
      <template v-slot:address="{ row }">
        <div>
          {{ row.province }}{{ row.province === row.city ? '' : row.city
          }}{{ row.district }}{{ row.address }}
        </div>
      </template>
    </avue-crud>
  </basic-container>
</template>

<script>
import { tableOption } from '@/const/crud/admin/baseMng';
import crudMixins from '@/mixins/crud';
import { addObj, delObj, fetchPage, putObj, getObj } from '@/api/core/base';
export default {
  name: 'BaseMng',
  mixins: [crudMixins],
  data() {
    return {
      tableOption,
      form: {},
    };
  },
  methods: {
    async uploadBefore(file, done, loading, column) {
      const isType =
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/jpeg' ||
        file.type === 'image/webp' ||
        file.type === 'image/heic';
      if (!isType) {
        loading();
        this.$message.error('仅支持上传JPG、PNG、JPEG、WEBP、HEIC格式图片!');
        return;
      }
      done();
    },
    //上传之前
    async uploadAfter(file, done, loading, column) {
      this.$refs.crud.clearValidate('files');
      done();
    },
    uploadExceed(limit, files, fileList, column) {
      console.log(limit, files, fileList, column);
      this.$message.error(`只能上传${limit}个文件`);
    },
    //文件大小
    uploadError(error, column) {
      if (error === '文件太大不符合') {
        this.$message.warning(`文件大小不能超过${column.fileSize / 1024}M`);
      }
    },
    // 获取列表
    async getList() {
      try {
        this.tableLoading = true;
        const params = {
          ...this.axiosPage,
          ...this.searchForm,
        };
        if (this.searchForm.openDate) {
          params.openDateStart = `${this.searchForm.openDate[0]} 00:00:00`;
          params.openDateEnd = `${this.searchForm.openDate[1]} 23:59:59`;
        }
        const { data } = await fetchPage(params);
        this.tableData = data.data.records;
        this.tableData.forEach((el) => {
          el.appUserName = el.appUserId;
        });
        this.page.total = data.data.total;
        this.tableLoading = false;
      } catch (error) {
        this.tableLoading = false;
        throw new Error(error);
      }
    },
    // 编辑
    async handleUpdate(row, index, done, loading) {
      try {
        const params = await this.getParams(row);
        await putObj(params);
        done();
        this.getList();
      } catch (error) {
        loading();
        throw new Error(error);
      }
    },
    async inverseCode(addressInfo) {
      return new Promise((resolve, reject) => {
        // 逆编码
        window.AMap.plugin('AMap.Geocoder', function () {
          var geocoder = new window.AMap.Geocoder({
            // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
            city: '全国',
          });
          var lnglat = [addressInfo[0], addressInfo[1]];
          geocoder.getAddress(lnglat, async function (status, result) {
            if (status === 'complete' && result.info === 'OK') {
              // result为对应的地理位置详细信息
              const res = result.regeocode.addressComponent;
              const addressInfoDetail = {
                // 地址信息
                longitude: addressInfo[0], // 经度
                latitude: addressInfo[1], // 纬度
                province: res.province, // 省
                city: res.city || res.province, // 市
                district: res.district, // 区
                address: addressInfo[2], // 详细地址
              };
              resolve(addressInfoDetail);
            }
          });
        });
      });
    },
    async getParams(row) {
      const {
        id,
        type,
        name,
        addressInfo,
        files,
        openDate,
        businessTime,
        introduction,
        appUserId,
        tag,
        cloudPhone,
        feature,
      } = row;
      const addressInfoDetail = await this.inverseCode(addressInfo);
      const params = {
        appUserId,
        id, // 对象id
        type, // 公益站类型
        name, // 公益站名称
        files: JSON.stringify(files), // 公益站图片
        tag,
        feature,
        picture: files[0],
        openDate: openDate
          ? openDate.split(' ').length > 1
            ? openDate
            : `${openDate} 00:00:00`
          : '', // 开业时间
        businessTime, // 营业时间
        introduction, // 说明
        cloudPhone,
        ...addressInfoDetail,
        // address: addressInfo.address, // 具体地址
        // longitude: addressInfo.longitude, // 经度
        // latitude: addressInfo.latitude, // 纬度
      };
      return params;
    },
    // 保存
    async handleSave(row, done, loading) {
      try {
        const params = await this.getParams(row);
        console.log('params', params);
        await addObj(params);
        done();
        this.getList();
      } catch (error) {
        loading();
        throw new Error(error);
      }
    },
    // 删除
    handleDelete: function (row, index) {
      this.$confirm('是否确认删除该公益站!', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return delObj(row.id);
        })
        .then(() => {
          this.$message.success('删除成功');
          this.getList();
        });
    },
    // 打开窗口前的拦截，针对编辑需要进行调用接口回显数据
    async beforeOpen(done, type) {
      console.log(this.form);
      // 如果不是新增
      if (type !== 'add') {
        const { data } = await getObj(this.form.id);
        this.form = data.data;
        console.log(this.form);
        this.form.files = JSON.parse(this.form.files);
        // const files = JSON.parse(data.data.files);
        // this.form.files = files[0].url;
        // 数据处理地址
        // this.form.addressInfo = {
        //   address: data.data.address,
        //   longitude: data.data.longitude,
        //   latitude: data.data.latitude,
        //   province: data.data.province,
        //   city: data.data.city,
        //   district: data.data.district,
        // };
        this.form.addressInfo = [
          data.data.longitude,
          data.data.latitude,
          data.data.address,
        ];
      }
      done();
    },
  },
};
</script>

<style lang="scss">
.dialog-base {
  .avue-upload {
    // position: absolute;
    // width: 100%;
    .avue-upload__avatar {
      width: 200px;
      height: 109px;
      line-height: 109px !important;
    }
  }
  .el-collapse-item__header {
    margin-bottom: 0;
  }
}
.base-crud {
  .avue-crud__search {
    .avue-form__menu {
      width: auto;
      padding: 0;
      text-align: right;
      flex: 1;
    }
  }
}
</style>
